package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class ReflectionCreateInstance {
    public static void main(String[] args) throws Exception {
        Class<?> userClass = Class.forName("reflection.User");
        //通过无参构造器获取对象实例
        Object o = userClass.newInstance();
        System.out.println(o);
        //通过public有参构造器获取对象实例
        Constructor<?> constructor = userClass.getConstructor(String.class);
        Object lihua = constructor.newInstance("lihua");
        System.out.println(lihua);

        //通过私有的有参构造器获取
        //获取到私有构造器对象
        Constructor<?> constructor1 = userClass.getDeclaredConstructor(String.class, int.class);
        //想要调用私有的构造器，需要用到爆破
        constructor1.setAccessible(true);//爆破
        Object wyx = constructor1.newInstance("wyx", 21);
        System.out.println(wyx);


        //
        Class<?> stuClass = Class.forName("reflection.Student");
        //获取对象实例
        Object o1 = stuClass.newInstance();
        //获取age属性
        Field age = stuClass.getField("age");
        //设置age属性
        age.set(o1,18);
        System.out.println(o1);

        //获取静态属性
        Field name = stuClass.getDeclaredField("name");
        //爆破
        name.setAccessible(true);
        name.set(o1,"jack");
        System.out.println(o1);
        //因为name是静态属性，因此o1可以写成null
        name.set(null,"jack");
        System.out.println(name.get(o1));
        System.out.println(name.get(null));


    }
}

class User{
    String name = "jack";
    int age = 10;

    public User(){}

    public User(String name) {
        this.name = name;
    }

    private User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

class Student{
    public int age;
    private static String name;

   public Student(){}

    @Override
    public String toString() {
        return "Student{" +
                "age=" + age + " " +
                "name=" + name +
                '}';
    }
}
